package com.lbssoft.gpsbd.controller;

import com.lbssoft.gpsbd.common.PropertiesUtil;
import com.lbssoft.gpsbd.common.Utils;
import com.lbssoft.gpsbd.model.Result;
import com.lbssoft.gpsbd.model.vo.Developer;
import com.lbssoft.gpsbd.model.vo.SystemProperty;
import com.lbssoft.gpsbd.service.InstallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Api("安装接口")
@RestController
@RequestMapping(value="/install")
public class InstallController {

	@Autowired
	InstallService installService;


	@ApiOperation(value="检查是否安装", notes="检查是否安装")
	@RequestMapping(value = "/check",method = {RequestMethod.GET})
	@ResponseBody
	public Result check() {
		Result result = new Result();
		PropertiesUtil pro = new PropertiesUtil("application.properties");
		String isInstall = pro.get("gpsbd.install").toString();
		result.setData(Boolean.parseBoolean(isInstall));

		return result;
	}

	@ApiOperation(value="第一步", notes="第一步系统许可证")
	@RequestMapping(value = "/first",method = {RequestMethod.GET})
	@ResponseBody
	public Result first() {
		Result result = new Result();
		result.setMsg("系统许可证文件");
		return result;
	}

	@ApiOperation(value="第二步", notes="第二创建密钥")
	@ApiImplicitParam(paramType="body",name = "developer", value = "开发者信息", dataType = "Developer")
	@RequestMapping(value = "/second",method = {RequestMethod.POST})
	@ResponseBody
	public Result second(@Validated @RequestBody Developer developer) {
		Result result = new Result();
		String  appSecret = installService.getAppSecret(developer);
		if(appSecret!=null){
			result.setData(appSecret);
			result.setMsg("AppSecret获取成功");
		}else{
			result.setMsg("AppSecret获取失败");
			result.setCode(1);
		}
		return result;
	}

	@ApiOperation(value="第三步", notes="系统参数设置")
	@RequestMapping(value = "/third",method = {RequestMethod.POST})
	@ResponseBody
	public Result third(@Validated @RequestBody SystemProperty property) {
		Result result = new Result();
		StringBuilder sb = new StringBuilder();
		boolean isCreate = false;
		boolean isImport = false;
		if(property.isCreateDataBase()){
			isCreate = installService.createDataBase(property);
			if(isCreate){
				sb.append("数据库创建成功，");
			}else{
				sb.append("数据库创建失败，");
				result.setCode(1);
			}
		}
		if(property.isInitData()){
			isImport = installService.importData(property);
			if(isImport){
				sb.append("数据库初始化成功，");
				installService.initProperties(property);

			}else{
				sb.append("数据库初始化失败，");
				result.setCode(1);
			}
		}
		if(result.getCode()==0){
			//安装成功重新启动服务
			Utils.runCommand("systemctl restart gpsbd.service");
		}
		result.setMsg(sb.toString());
		return result;
	}
	
}